import md5 from 'blueimp-md5';

const config = {
  url: 'http://uip.innjia.com/api/InnjiaUIP', // 正式服
  // url: 'http://192.168.1.7:13841/api/innjiauip', // 王西星
  // url: 'http://testuip.innjia.com/test/api/innjiauip', // 测试
  // url: 'http://testuip.innjia.com/pre/api/innjiauip', // 预生产
  appid: 'H5',
  key: 'innjia2016111703'
};

// 对象键值排序
const orderObj = (obj) => {
  let o = {};
  Object.keys(obj).forEach((key) => {
    o[key] = obj[key];
  });
  return o;
};

// 对象按`name1=value1&name2=value2`序列化
const param = (obj = {}) => {
  let arr = [];
  for (let i in obj) {
    arr.push(i + '=' + obj[i]);
  }
  return arr.join('&');
};

// 生成带有签名的数据
const signData = (methodId, data) => {
  let result = {
    appid: config.appid,
    methodId,
    methodParam: JSON.stringify(data),
    nonce: Math.random().toString(),
    timestamp: new Date().getTime().toString(),
  };
  // MD5字符串参数
  let str = decodeURIComponent(param(orderObj(result)));
  str += '&key=' + config.key;
  result.signature = md5(str);
  return result;
};

// 生成带有签名的请求数据
const handleData = ({ methodId, data } = { methodId: '', data: {} }) => {
  data = signData(methodId, data);
  return data;
};


export default {
  handleData,
  url: config.url
};
